package com.rookie.tool.module.util.excel.handle;

import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import com.rookie.tool.module.util.excel.SelectConfig;
import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.util.CellRangeAddressList;

import java.util.List;

/**
 * @author rookie
 */
public class ExcelSheetWriteHandle implements SheetWriteHandler {

    private List<SelectConfig> selectConfig;

    public void setSelectConfig(List<SelectConfig> selectConfig) {
        this.selectConfig = selectConfig;
    }

    @Override
    public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {

    }

    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        DataValidationHelper helper = writeSheetHolder.getSheet().getDataValidationHelper();

        if (selectConfig != null && selectConfig.size() > 0){
            for(SelectConfig tmp : selectConfig){
                CellRangeAddressList cellRangeAddressList = new CellRangeAddressList(tmp.getStartY(), tmp.getEndY(),tmp.getStartX(), tmp.getEndX());
                DataValidationConstraint constraint = helper.createExplicitListConstraint(tmp.getList());
                DataValidation dataValidation = helper.createValidation(constraint, cellRangeAddressList);
                writeSheetHolder.getSheet().addValidationData(dataValidation);
            }
        }
    }
}
